package com.sendi.system.action;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import net.sf.json.JSONArray;

import org.hibernate.Session;

import com.sendi.system.entity.Functionmoudle;
import com.sendi.system.entity.SysHostPower;
import com.sendi.system.entity.SysHostTree;
import com.sendi.system.entity.SystemPower;
import com.sendi.system.util.tree.MoudleTreeCheckData;

/*
 * 该类在生成模块树跟设备时时，没有迭代全部的树数据，所以会存在一个问题，当用户重新保存模块权限时，
 * 由于有的没有加载，所以点击保存时，部分权限信息将丢失
 * 需要完善成一性加载全部数据
 */
public class SystemPowerAction extends SysAction {

	private Integer useroleid;
	private String powerstring;
	/*
	 * 生成 系统权限树
	 */
     public void generateSysPowerTree()
      {
    	 Session session=this.getHibernateSession();
    	 String hql="from Functionmoudle where  parentid="+this.Treeid;
  	    List datas=null;
 	 	datas=this.getListData(hql,session);
 	    ArrayList<MoudleTreeCheckData> children=new ArrayList<MoudleTreeCheckData>();
  	 
 	  	hql="from SystemPower where roleid in("+useroleid+")";
	 
		HashMap<String,String> powerMap=new HashMap<String, String>();
	 
		List result3=getListData(hql,session);
	 
	    for(Object o:result3)
	    {
	    	SystemPower sp=(SystemPower)o;
	    	powerMap.put(sp.getMoudleid()+"", sp.getPowerstate());
	    }
 		for(Object o:datas)
 		{
 			MoudleTreeCheckData ct=new MoudleTreeCheckData();
 			Functionmoudle f=(Functionmoudle)o;
 		 	ct.setId(f.getId());
 		   
 			ct.setLeaf(f.getIsleaf().equals("on")?true:false);
 			if(f.getMoudletype().equals("t")) //如果是3级模块，有可能存在按钮这个功能节点
 			{
 				ct.setLeaf(false);
 			}
 			ct.setText(f.getMoudletitle());
 		    if(powerMap!=null&&powerMap.get(f.getId()+"")!=null)
 		    {
 		    	ct.setChecked(powerMap.get(f.getId()+""));
 		    }
 			children.add(ct);
 			 
 	 	}
 		   String jsons = JSONArray.fromObject(children).toString();
 	      
 	       writeResponseText(jsons);
			
	 }
     
     /*
      * 生成设备权限树
      */
     public void generateSysHostPowerTree()
     {
   	   String hql="from SysHostTree where  parentid="+this.Treeid;
   	   Session session=this.getHibernateSession();
	 	List datas=null;
		datas=this.getListData(hql,session);
	    ArrayList<MoudleTreeCheckData> children=new ArrayList<MoudleTreeCheckData>();
	   	hql="from SysHostPower where roleid in("+useroleid+")";
	 
		HashMap<String,String> powerMap=new HashMap<String, String>();
	 
		List result3=this.getListData(hql,session);
 
	    for(Object o:result3)
	    {
	    	SysHostPower sp=(SysHostPower)o;
	    	powerMap.put(sp.getHostreeId()+"", sp.getPowerstate());
	    }
		for(Object o:datas)
		{
			MoudleTreeCheckData ct=new MoudleTreeCheckData();
			SysHostTree f=(SysHostTree)o;
		 	ct.setId(f.getId());
		   
			ct.setLeaf(f.getIshost().equals("y")?true:false);
			ct.setText(f.getNodeName());
		    if(powerMap!=null&&powerMap.get(f.getId()+"")!=null)
		    {
		    	ct.setChecked(powerMap.get(f.getId()+""));
		    }
			children.add(ct);
			 
	 	}
		   String jsons = JSONArray.fromObject(children).toString();
		   
	        writeResponseText(jsons);
			
	 }
     
     
     /*
      * 保存角色权限
      */
     public void saveSyspower()
     {
     	 String sql="delete from system_power  WHERE system_power.roleid ="+this.useroleid;
		 Connection con=this.serviceSupportImp.getDao().getSessionFactory().openSession().connection();
		 Statement state;
		try {
			state = con.createStatement();
			state.executeUpdate(sql);
		 	String sql2="insert into system_power (roleid,moudleid,powerstate) values (?,?,?)";
		 	if(this.powerstring!=null&&this.powerstring.trim().length()>0)
		 	{
		 		String a[]=this.powerstring.split(",");
		 	    PreparedStatement psd=con.prepareStatement(sql2);
		 		for(String b:a)
			 	{
			 		String t[]=b.split("-");
			 		if(t.length==2)
			 		{
			 			psd.setInt(1,this.useroleid);
				 		psd.setInt(2,Integer.parseInt(t[0]));
				 		psd.setString(3,t[1]);
				 		psd.addBatch();
			 		}
			 	
			 	}
		 		psd.executeBatch();
		  	}
		 	 writeResponseText("{success:true,msg:'success'}"); 
		 	 reloadSysPower();
		 	 return;
		 	
			
		} catch (SQLException e) {
			 
			e.printStackTrace();
		}
		finally
		{
			try {
				con.close();
			} catch (SQLException e) {
			 
				e.printStackTrace();
			}
		}
	  	 writeResponseText("{success:false,msg:'faild'}"); 
     }
     
 	public void reloadSysPower()
	{
	     ///重新加载内存中的权限信息
	     String hql7="from SystemPower";
 	     HashMap<String,SystemPower> systemPower=(HashMap<String,SystemPower>)applicationContextHelper.servletContext.getAttribute("sendi_sys_moudlePower_info");
 	    systemPower.clear();
 	     List datas7=this.getListData(hql7);
		 for(Object o7:datas7)
		 {
			 SystemPower slb=(SystemPower)o7;
			 systemPower.put(slb.getId()+"",slb);
		 }
	  
	}
     
     /*
      * 保存设备权限
      */
     public void saveSysHostpower()
     {
     	 String sql="delete from sys_host_power  WHERE sys_host_power.roleid ="+this.useroleid;
		 Connection con=this.serviceSupportImp.getDao().getSessionFactory().openSession().connection();
		 Statement state;
		try {
			state = con.createStatement();
			state.executeUpdate(sql);
		 	String sql2="insert into sys_host_power (roleid,hostree_id,powerstate) values (?,?,?)";
		 	if(this.powerstring!=null&&this.powerstring.trim().length()>0)
		 	{
		 		String a[]=this.powerstring.split(",");
		 	    PreparedStatement psd=con.prepareStatement(sql2);
		 		for(String b:a)
			 	{
			 		String t[]=b.split("-");
			 		if(t.length==2)
			 		{
			 			psd.setInt(1,this.useroleid);
				 		psd.setInt(2,Integer.parseInt(t[0]));
				 		psd.setString(3,t[1]);
				 		psd.addBatch();
			 		}
			 	
			 	}
		 		psd.executeBatch();
		  	}
		 	 writeResponseText("{success:true,msg:'success'}"); 
		 	reloadSysHostpower();
		 	 return;
		 	
			
		} catch (SQLException e) {
			 
			e.printStackTrace();
		}
		finally
		{
			try {
				con.close();
			} catch (SQLException e) {
			 
				e.printStackTrace();
			}
		}
	  	 writeResponseText("{success:false,msg:'faild'}"); 
	  
     }
     
     public void reloadSysHostpower()
     {
    	 System.out.println("reloadSysHostpower--------------------------------------");
    	 String hql8="from SysHostPower";
		 List datas8=this.getListData(hql8);
		 HashMap<String,SysHostPower> systemhostPower=(HashMap<String,SysHostPower>) applicationContextHelper.servletContext.getAttribute("sendi_sys_hostPower_info");
		 systemhostPower.clear();
		 for(Object o8:datas8)
		 {
			 SysHostPower slb=(SysHostPower)o8;
			 systemhostPower.put(slb.getId()+"",slb);
			 System.out.println(slb.getHostreeId());
		 }
	   }
	public Integer getUseroleid() {
		return useroleid;
	}
	public void setUseroleid(Integer useroleid) {
		this.useroleid = useroleid;
	}
	public String getPowerstring() {
		return powerstring;
	}
	public void setPowerstring(String powerstring) {
		this.powerstring = powerstring;
	}
}
